//
//  DHProductDetailViewController.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/1/12.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHProductDetailViewController.h"
#import "DHProductCollectionViewCell.h"
#import "DHS2_ProductInfoController.h"
#import "DHSizeScrollView.h"

@interface DHProductDetailViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout, DHSizeScrollViewDelegate, UIScrollViewDelegate>

@property (strong, nonatomic) NSString *productID;
@property (strong, nonatomic) NSString *brandName;

@property (strong, nonatomic) Product *product;

@property (weak, nonatomic) IBOutlet UIScrollView *contentScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *coverScrollView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *coverScrollViewHeightLayout;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pageControlTopLayout;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIButton *addCartButton;
@property (weak, nonatomic) IBOutlet DHSizeScrollView *sizeScrollView;
@property (weak, nonatomic) IBOutlet UIButton *infoButton;

// 关联产品
@property (weak, nonatomic) IBOutlet UICollectionView *relatedCollectionView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *relatedCollectionViewHeightLayout;


// 点赞view
@property (weak, nonatomic) IBOutlet UIView *likeView;
@property (strong, nonatomic) UIButton *likeButton;
@property (strong, nonatomic) UILabel *likeNumberLabel;

@property (strong, nonatomic) NSMutableArray *relatedArray;

@property (strong, nonatomic) NSString *selectedSizeID;

@end

@implementation DHProductDetailViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (NSMutableArray *)relatedArray{
    if (!_relatedArray) {
        _relatedArray = [NSMutableArray array];
    }
    return _relatedArray;
}

- (instancetype)initWithProductID:(NSString *)productID brandName:(NSString *)brandName
{
    self = [super init];
    if (self) {
        self.productID = productID;
        self.brandName = brandName;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.addCartButton.enabled = NO;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.title = self.brandName;
    [self initView];
    [self loadProductInfo];
    [self loadRelatedData];
}

- (void)initView{
    self.coverScrollViewHeightLayout.constant = self.view.height;
    self.pageControlTopLayout.constant = self.view.height - 70;
    
    self.bottomView.layer.cornerRadius = 2;
    self.bottomView.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.bottomView.layer.shadowRadius = 5;
    self.bottomView.layer.shadowOpacity = 0.5;
    self.bottomView.layer.shadowOffset  = CGSizeMake(0, 0);

    self.coverScrollView.pagingEnabled = YES;
    
    self.likeButton = [[UIButton alloc] initWithFrame:CGRectMake(self.likeView.width/2 - 20, 22, 40, 40)];
    [self.likeButton setImage:[UIImage imageNamed:@"article_unlike"] forState:UIControlStateNormal];
    self.likeNumberLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.likeButton.bottom, self.likeView.width, 20)];
    self.likeNumberLabel.textColor = [UIColor colorWithHexString:@"#939393"];
    self.likeNumberLabel.font = [UIFont systemFontOfSize:12];
    self.likeNumberLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.likeView addSubview:self.likeButton];
    [self.likeView addSubview:self.likeNumberLabel];
    
    // 喜欢事件
    [self.likeButton bk_addEventHandler:^(id sender) {
        [[DHNetAPIClient shareDHNetAPIClient] request_user_likeAndOrigin:self.product._id andBlock:^(id data, NSError *error) {
            self.product.liked = [NSNumber numberWithBool:![self.product.liked boolValue]];
            [self changeLikeButtonImg];
        }];
    } forControlEvents:UIControlEventTouchUpInside];
    
    self.sizeScrollView.delegate = self;
    
    self.relatedCollectionView.dataSource = self;
    self.relatedCollectionView.delegate = self;
    self.relatedCollectionView.scrollEnabled = NO;
    [self.relatedCollectionView registerNib:[UINib nibWithNibName:@"DHProductCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:kDHProductCollectionViewCell];
    
    // 添加购物车
    [self.addCartButton bk_addEventHandler:^(id sender) {
        if (self.selectedSizeID) {
            [[DHNetAPIClient shareDHNetAPIClient] request_cart_addWithParams:@{@"type":@"租赁",@"_id":self.selectedSizeID} andBlock:^(id data, NSError *error) {
                [NSObject showHudTipStr:@"成功添加至购物车"];
                [[GlobalManager shareGlobalManager] refreshCartNumberAndBlock:^(id data, NSError *error) {
                    
                }];
            }];
        }else{
            [NSObject showHudTipStr:@"请选择一个尺寸"];
        }
    } forControlEvents:UIControlEventTouchUpInside];
}

- (void)refreshUIData{
    // pageControl
    self.pageControl.numberOfPages = self.product.snapshots.count;
    
    // coverScrollView
    [self.coverScrollView removeAllSubviews];
    self.coverScrollView.contentSize = CGSizeMake(self.contentScrollView.width * self.product.snapshots.count, self.coverScrollView.height);
    [self.product.snapshots enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(idx * self.coverScrollView.width, 0, self.coverScrollView.width, self.coverScrollView.height)];
        imgView.contentMode = UIViewContentModeCenter;
        imgView.layer.masksToBounds = YES;
        [imgView dh_setImageURLString:obj];
        [self.coverScrollView addSubview:imgView];
    }];
    
    // like view
    [self.likeNumberLabel setText:[NSString stringWithFormat:@"%@个赞",[self.product.like_count stringValue]]];
    [self.product.liked boolValue]? [self.likeButton setImage:[UIImage imageNamed:@"article_like"] forState:UIControlStateNormal]:[self.likeButton setImage:[UIImage imageNamed:@"article_unlike"] forState:UIControlStateNormal];
    
    // size scrollview
    [self.sizeScrollView loadSizesData:self.product.sizes];
}

- (void)changeLikeButtonImg{
    if ([self.product.liked boolValue]) {
        [self.likeButton setImage:[UIImage imageNamed:@"product_like"] forState:UIControlStateNormal];
    }else{
        [self.likeButton setImage:[UIImage imageNamed:@"product_unlike"] forState:UIControlStateNormal];
    }
}

// 产品详情
- (void)loadProductInfo{
    [[DHNetAPIClient shareDHNetAPIClient] request_products_detailWithDictionary:@{@"product_id":self.productID} andBlock:^(id data, NSError *error) {
        self.product = [Product modelWithDictionary:[data objectForKey:@"product"]];
        [self refreshUIData];
    }];
}

// 商品信息
- (IBAction)infoAction:(id)sender {
    DHS2_ProductInfoController *infoController = [[DHS2_ProductInfoController alloc] initWithProduct:self.product];
    [self.navigationController pushViewController:infoController animated:YES];
}

// 相关产品
- (void)loadRelatedData{
    [[DHNetAPIClient shareDHNetAPIClient] request_products_relatedWithDictionary:@{@"_id":self.productID} andBlock:^(id data, NSError *error) {
        self.relatedArray = [data objectForKey:@"products"];
        if (self.relatedArray.count % 2 > 0) {
            self.relatedCollectionViewHeightLayout.constant = (self.relatedArray.count / 2) * 317 + 317 + 20;
        }else{
            self.relatedCollectionViewHeightLayout.constant = (self.relatedArray.count / 2) * 317 + 20;
        }
        self.contentScrollView.contentSize = CGSizeMake(self.contentScrollView.width, self.relatedCollectionView.top + self.relatedCollectionViewHeightLayout.constant + 80);
        [self.relatedCollectionView reloadData];
    }];
}

#pragma mark - DHSizeScrollViewDelegate
- (void)sizeScrollViewSelected:(NSString *)size_id{
    NSLog(@"selectedSizeID:::%@",size_id);
    self.selectedSizeID = size_id;
    if (self.selectedSizeID) {
        [self.addCartButton setImage:[UIImage imageNamed:@"detail_add_cart"] forState:UIControlStateNormal];
        self.addCartButton.enabled = YES;
        [self.product.sizes enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([[obj objectForKey:@"_id"] isEqualToString:self.selectedSizeID]) {
                [self.infoButton setTitle:[NSString stringWithFormat:@"￥%.2f",[[obj objectForKey:@"lease_price"] floatValue]] forState:UIControlStateNormal];
                [self.infoButton setTitleColor:[UIColor colorWithHexString:@"#1A81FE"] forState:UIControlStateNormal];
                *stop = YES;
            }
        }];
    }else{
        [self.addCartButton setImage:[UIImage imageNamed:@"detail_add_cart_no"] forState:UIControlStateNormal];
        self.addCartButton.enabled = NO;
        [self.infoButton setTitle:@" 商品信息" forState:UIControlStateNormal];
        [self.infoButton setTitleColor:[UIColor colorWithHexString:@"#9B9B9B"] forState:UIControlStateNormal];
    }
}

#pragma mark - UICollectionViewDataSource and UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.relatedArray.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    DHProductCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kDHProductCollectionViewCell forIndexPath:indexPath];
    Product *product = [Product modelWithDictionary:self.relatedArray[indexPath.row]];
    [cell updateWithProduct:product];
    return cell;
}

#pragma mark ---- UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return (CGSize){kScreenWidth/2,317};
}

// 两行之间的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

// 两个cell之间的最小间距，是由API自动计算的，只有当间距小于该值时，cell会进行换行
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    Product *product = [Product modelWithDictionary:self.relatedArray[indexPath.row]];
    DHProductDetailViewController *pdController = [[DHProductDetailViewController alloc] initWithProductID:product._id brandName:product.brand.name];
    [self.navigationController pushViewController:pdController animated:YES];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger pageIndex = scrollView.contentOffset.x / self.coverScrollView.width;
    self.pageControl.currentPage = pageIndex;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
